<template>  
	<div style="padding: 20px; background: #f5f7fa">  
		<!-- 搜索区域 -->  
		<div class="search-area card">  
			<el-form :model="formData" size="mini"  label-width="100px" label-position="left" inline>  
				<el-row :gutter="20">  
					<el-row :gutter="20">  
					<el-col :span="6">  
						<el-form-item label="客户名称">  
							<el-input v-model="formData.customerName" clearable placeholder="输入客户名称"></el-input>  
						</el-form-item>  
					</el-col>  
					<el-col :span="6">  
						<el-form-item label="客户经理">  
							<el-select v-model="formData.manager" clearable  placeholder="请选择">  
								<el-option label="张三" value="张三"></el-option>  
								<el-option label="李四" value="李四"></el-option>  
							</el-select>  
						</el-form-item>  
					</el-col>  
					<el-col :span="6">  
						<el-form-item label="客户状态">  
							<el-select v-model="formData.customerStatus" clearable placeholder="请选择">  
								<el-option label="待定" value="pending"></el-option>  
								<el-option label="合作中" value="active"></el-option>  
							</el-select>  
						</el-form-item>  
					</el-col>  
					<el-col :span="6">  
						<!-- <el-form-item label="行业">  
							<el-select v-model="formData.industry" placeholder="请选择">  
								<el-option label="互联网" value="it"></el-option>  
								<el-option label="金融" value="finance"></el-option>  
							</el-select>  
						</el-form-item>   -->
						<!-- 功能按钮 -->  
					<el-button type="primary" @click="handleSearch">搜索</el-button>  
					<el-button type="success" @click="openDialog()">新增</el-button>  
					</el-col>  
				</el-row>   
				</el-row>  
				
			</el-form>  
		</div>  
		  
		<!-- 表格部分 -->  
		<div class="table-container card">  
			<el-table   
				:data="tableData"   
				style="width: 100%"   
				border   
				size="mini"
				:header-cell-style="{background:'#f5f7fa',color:'#606266',fontSize:'14px',fontWeight:'600',textAlign:'center'}"
				:cell-style="{fontSize:'12px',padding:'6px 0',textAlign:'center'}"
				height="650"
			>  
				<el-table-column prop="visitType" label="拜访类型" width="150"></el-table-column> 
				<el-table-column prop="customerName" label="客户名称" width="150"></el-table-column>  
				<el-table-column prop="address" label="客户地址" width="200"></el-table-column>  
				<el-table-column prop="visitTarget" label="拜访对象" width="120"></el-table-column>  
				<el-table-column prop="phone" label="联系方式" width="150"></el-table-column>  
				<el-table-column prop="visitPurpose" label="拜访目的" width="150"></el-table-column>  
				<el-table-column prop="visitTime" label="拜访时间" width="150" :formatter="formatVisitTime"></el-table-column>  
				<el-table-column prop="visitLocation" label="拜访地点" width="150"></el-table-column>  
				<el-table-column prop="starLevel" label="星级" width="150"></el-table-column>  
				 
				<el-table-column prop="progress" label="进展与结果" width="150"></el-table-column>  
				<!-- <el-table-column prop="photoReview" label="照片查看" width="120">  
					<template #default="scope">  
						<el-button type="text" size="small" @click="viewPhoto(scope)">查看</el-button>  
					</template>  
				</el-table-column>   	   -->
				<el-table-column label="操作" width="120">
					<template #default="scope">  
						<el-button type="text" size="small" @click="openDialog(scope.row)">快捷编辑</el-button>  
						<!-- <el-button type="text" size="small" @click="delVisit(scope.row)">删除</el-button>   -->
					</template>  
					
				</el-table-column>  
			</el-table>  
		</div>  
		<!-- 分页 -->  
		 <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="formData.pageNum"
        :limit.sync="formData.pageSize"
        @pagination="getVisitList"
      />
		<!-- 优化美化的弹窗 -->
		<el-dialog 
			:title="isEdit ? '编辑拜访记录' : '新增拜访记录'" 
			:visible.sync="dialogVisible" 
			width="900px" 
			class="visit-dialog"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			top="5vh"
		>
			
			<el-form 
				:model="dialogForm" 
				ref="dialogForm" 
				size="medium" 
				label-width="120px" 
				class="visit-form"
				:rules="formRules"
			>
				<!-- 客户基本信息 -->
				<div class="form-section customer-section">
					<div class="section-header">
						<i class="el-icon-user section-icon"></i>
						<span class="section-title">客户基本信息</span>
					</div>
					<div class="section-content">
						<el-row :gutter="24">
							<el-col :span="12">
								<el-form-item label="客户名称" prop="customerName" class="required-field">
									<el-autocomplete  
										v-model="dialogForm.customerName"  
										placeholder="请输入客户名称进行搜索"  
										clearable  
										@select="onSelectCustomerName"  
										:fetch-suggestions="fetchCustomerData"  
										:trigger-on-focus="false"
										class="customer-autocomplete"
										prefix-icon="el-icon-search"
										:debounce="300"
									/>  
									<div class="field-tip">支持模糊搜索，输入关键字即可</div>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="客户地址" prop="address">
									<el-input 
										v-model="dialogForm.address" 
										placeholder="请输入客户地址" 
										clearable 
										prefix-icon="el-icon-location-outline"
									/>
									
								</el-form-item>
							</el-col>
						</el-row>
					</div>
				</div>

				<!-- 拜访详情 -->
				<div class="form-section visit-section">
					<div class="section-header">
						<i class="el-icon-chat-line-square section-icon"></i>
						<span class="section-title">拜访详情</span>
					</div>
					<div class="section-content">
						<el-row :gutter="24">
							<el-col :span="12">
								<el-form-item label="拜访类型" prop="visitType" class="required-field">
									<el-select 
										v-model="dialogForm.visitType" 
										placeholder="请选择拜访类型"
										style="width: 100%"
									>
										<el-option label="初次拜访" value="初次拜访">
											<span style="float: left">初次拜访</span>
											<span style="float: right; color: #8492a6; font-size: 13px">首次接触</span>
										</el-option>
										<el-option label="续约洽谈" value="续约洽谈">
											<span style="float: left">续约洽谈</span>
											<span style="float: right; color: #8492a6; font-size: 13px">合作续签</span>
										</el-option>
										<el-option label="项目跟进" value="项目跟进">
											<span style="float: left">项目跟进</span>
											<span style="float: right; color: #8492a6; font-size: 13px">进度沟通</span>
										</el-option>
										<el-option label="售后服务" value="售后服务">
											<span style="float: left">售后服务</span>
											<span style="float: right; color: #8492a6; font-size: 13px">问题解决</span>
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="联系方式" prop="phone">
									<el-input 
										v-model="dialogForm.phone" 
										placeholder="请输入联系方式" 
										clearable 
										prefix-icon="el-icon-phone"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="24">
							<el-col :span="12">
								<el-form-item label="拜访对象" prop="visitTarget">
									<el-input 
										v-model="dialogForm.visitTarget" 
										placeholder="请输入拜访对象" 
										clearable 
										prefix-icon="el-icon-user-solid"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="24">
							<el-col :span="24">
								<el-form-item label="拜访目的" prop="visitPurpose">
									<el-input 
										v-model="dialogForm.visitPurpose" 
										type="textarea"
										:rows="2"
										placeholder="请详细描述拜访目的和期望达成的目标" 
										resize="none"
										maxlength="200"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="24">
							<el-col :span="24">
								<el-form-item label="进展结果" prop="progress">
									<el-input 
										v-model="dialogForm.progress" 
										type="textarea"
										:rows="3"
										placeholder="请详细记录拜访过程、客户反馈、达成的共识以及后续跟进计划" 
										resize="none"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
					</div>
				</div>

				<!-- 额外信息 -->
				<!-- <div class="form-section">
					<div class="section-title">额外信息</div>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="星级" prop="starLevel">
								<el-input v-model="dialogForm.starLevel" placeholder="请输入星级" clearable />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="最后沟通时间" prop="lastCommunicationTime">
								<el-date-picker v-model="dialogForm.lastCommunicationTime" type="date" placeholder="请选择最后沟通时间" value-format="yyyy-MM-dd" />
							</el-form-item>
						</el-col>
					</el-row>
				</div> -->
			</el-form>

			</el-form>
			
			<!-- 优化的底部按钮 -->
			<div slot="footer" class="dialog-footer-enhanced">
				<div class="footer-buttons">
					<el-button 
						size="medium" 
						@click="handleCancel"
						class="cancel-btn"
					>
						<i class="el-icon-close"></i>
						取消
					</el-button>
					<el-button 
						type="primary" 
						size="medium"
						@click="handleSubmit"
						class="submit-btn"
						:loading="submitLoading"
					>
						<i :class="isEdit ? 'el-icon-check' : 'el-icon-plus'"></i>
						{{ isEdit ? '保存修改' : '确认新增' }}
					</el-button>
				</div>
			</div>
		</el-dialog>
	</div>  
</template>  
<script>  
import moment from 'moment';  
import { addVisit, visitList, updateVisit, Clientlist,delContract,queryMesBycustomerName } from "@/api/monitor/customer";  
export default {  
	data() {  
		return {  
			selectedCustomerName: '', // 选中的客户名称 
			tableHeaderStyle: {  
				backgroundColor: '#f0f2f5', // 表头背景色  
				color: '#409EFF',           // 表头文字颜色  
				fontWeight: 'bold',         // 表头文字加粗  
				textAlign: 'center'         // 表头文字居中对齐  
			},
			selectedRow: null,  // 当前选中行  
			dialogVisible: false,   // 控制弹窗显示  
			isEdit: false,          // 标记是否为编辑模式 
			formData: {  
				customerName: "",  
				manager: "",  
				customerStatus: "",  
				industry: "",  
				pageNum: 1,
				pageSize: 15
			},  
			tableData: [],  
			currentPage: 1,  
			pageSize: 10,  
			total: 2,  
			dialogVisible: false,  
			dialogForm: {  
				customerName: "",  
				customerCode :"",
				address: "",  
				visitTarget: "",  
				phone: "",  
				visitPurpose: "",  
				visitTime: "",  
				visitLocation: "",  
				visitType: "",  
				progress: "",  
				lastCommunicationTime: ""  ,
				manager: ""  ,
				starLevel :'',
				isDeleted : ''
			},
			// 表单验证规则
			formRules: {
				customerName: [
					{ required: true, message: '请输入客户名称', trigger: 'blur' },
					{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
				],
				visitType: [
					{ required: true, message: '请选择拜访类型', trigger: 'change' }
				],
				phone: [
					{ pattern: /^1[3-9]\d{9}$|^\d{3,4}-\d{7,8}$/, message: '请输入正确的手机号或座机号', trigger: 'blur' }
				],
				visitPurpose: [
					{ max: 200, message: '拜访目的不能超过200个字符', trigger: 'blur' }
				],
				progress: [
					{ max: 500, message: '进展结果不能超过500个字符', trigger: 'blur' }
				]
			},
			// 提交加载状态
			submitLoading: false  
		};  
	},  
	created() {  
    	this.getVisitList()  
  	} ,
	methods: {  
		// 优化的客户名称模糊搜索
		fetchCustomerData(query, callback) {  
			console.log(query)
			if (!query || query.trim().length < 1) {
				callback([]);
				return;
			}
			
			try {  
				// 这里是模糊查询接口，后续可以替换为实际的接口名
				queryMesBycustomerName(query.trim()).then(response => {  
					console.log("客户名称模糊搜索结果:", response);
					if (response.data && response.data.length > 0) {  
						// 格式化搜索结果，添加更多信息显示
						const suggestions = response.data.map(item => ({
							value: item.customerName,
							label: item.customerName,
							address: item.address || '',
							phone: item.phone || '',
							id: item.id,
							starLevel: item.starLevel || ''
						}));

						callback(suggestions);
					} else {  
						callback([]);  
					}  
				}).catch(error => {
					console.error('客户搜索接口调用失败:', error);
					callback([]);
				}); 
			} catch (error) {   
				console.error('客户搜索异常:', error);
				callback([]);  
			}  
		},  
		onSelectCustomerName(selectedName) {  
			this.dialogForm.customerName = selectedName.value; // 将选中的客户名称填入输入框  
			this.queryBackend(this.dialogForm.customerName); // 执行查询后台操作
		},  
		queryBackend(customerName) {  
			// 在这里执行后台查询操作  
			queryMesBycustomerName(customerName).then(response => {  
					if (response.data && response.data.length === 0) {  
						this.customerOptions = []; // 清空选项
						//错误提示
						this.$message.error('未找到客户数据');
					} else {  
						// 如果找到数据，可以根据需要处理  
						this.dialogForm.address = response.data[0].address;
						this.dialogForm.starLevel = response.data[0].starLevel;
						this.dialogForm.phone = response.data[0].phone;
						this.dialogForm.customerCode = response.data[0].customerCode;
					}  
				}); 
		},  
		
		// 新增单选逻辑  
		handleRadioChange(row) {  
			this.selectedRow = row;  
		},  

		// 点击行触发单选  
		handleRowClick(row) {  
			this.selectedRow = row;  
		},  
		// 获取列表数据  
		getVisitList() {  
			this.loading = true; 
			visitList(this.formData).then(response => {  
				console.log("初始化数据室")
				console.log(response)
				this.tableData = response.rows;
				this.total = response.total;  
				this.loading = false;  
			}); 
		},  
		// 格式化日期  
		formatDate(date, format = 'YYYY-MM-DD') {  
			if (!date) return ''  
			return moment(date).format(format)  
		},
		// 格式化拜访时间为年月日时分格式
		formatVisitTime(row, column, cellValue) {
			if (!cellValue) return ''
			return moment(cellValue).format('YYYY-MM-DD HH:mm')
		},
		delVisit(row) {  
			this.$confirm('您确认删除这一项吗？', '警告', {  
				confirmButtonText: '确定',  
				cancelButtonText: '取消',  
				type: 'warning',  
			})  
			.then(() => {  
				this.dialogForm = { ...row };   
				this.dialogForm.isDeleted = '1';
				updateVisit(this.dialogForm).then(response => {  
					this.getVisitList();
				}); 
				console.log(row);
			})  
			.catch(() => {  
				// 用户点击取消  
				console.log('删除操作已被取消');  
			});  
		},
		// 打开弹窗（新增/编辑）  
		openDialog(row = null) {  
			this.isEdit = !!row;  // 如果传入行数据则为编辑模式  
			if (this.isEdit) {  
				// 编辑模式：填充已有数据  
				this.dialogForm = { ...row };   
			} else {  
				// 新增模式：清空表单  
				this.resetForm();  
			}  
			this.dialogVisible = true;  
		},  
		// 重置表单
		resetForm() {
			if (this.$refs.dialogForm) {
				this.$refs.dialogForm.resetFields();
			}
			this.dialogForm = {
				customerName: "",  
				address: "",  
				visitTarget: "",  
				phone: "",  
				visitPurpose: "",  
				visitTime: "",  
				visitLocation: "",  
				visitType: "",  
				progress: "",  
				lastCommunicationTime: ""  ,
				manager: "",
				starLevel :'',
				isDeleted: ''
			};
			this.submitLoading = false;
		},
		
		
		// 取消操作
		handleCancel() {
			this.$confirm('确认取消操作？未保存的数据将会丢失', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '继续编辑',
				type: 'warning'
			}).then(() => {
				this.dialogVisible = false;
				this.resetForm();
			}).catch(() => {
				// 用户选择继续编辑，不做任何操作
			});
		},
		
		// 优化的提交处理
		handleSubmit() {  
			// 表单验证
			this.$refs.dialogForm.validate((valid) => {
				if (!valid) {
					this.$message.error('请检查表单信息是否填写正确');
					return false;
				}
				
				this.submitLoading = true;
				
				if (this.isEdit) {
					// 编辑模式
					updateVisit(this.dialogForm).then(response => {  
						this.submitLoading = false;
						this.$message.success('编辑成功！');
						this.dialogVisible = false;
						this.resetForm();
						this.getVisitList();
					}).catch(error => {
						this.submitLoading = false;
						this.$message.error('编辑失败，请重试');
						console.error('编辑失败:', error);
					}); 
				} else {
					// 新增模式
					this.dialogForm.isDeleted = '0';
					addVisit(this.dialogForm).then(response => {  
						this.submitLoading = false;
						this.$message.success('新增成功！');
						this.dialogVisible = false;
						this.resetForm();
						this.getVisitList();
					}).catch(error => {
						this.submitLoading = false;
						this.$message.error('新增失败，请重试');
						console.error('新增失败:', error);
					}); 
				}
			});
		},  
		handleSearch() {  
			console.log("搜索", this.formData);  
			this.getVisitList();
		},  
		handlePageChange(page) {  
			this.currentPage = page;  
			console.log("分页变化：" + page);  
		},  
		viewPhoto(scope) {  
			console.log("查看照片：", scope.row);  
		}  
	}  
};  
</script>  

<style scoped>  
/* 基础样式 */
.el-table .el-radio {  
	vertical-align: middle;  
}  

.el-table__body tr.current-row > td {  
	background-color: #f0f9eb !important;  
}  

.card {  
	background: #ffffff;  
	padding: 20px;  
	border-radius: 8px;  
	margin-bottom: 20px;  
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);  
}  

.btn-group {  
	margin-top: 15px;  
}  

.pagination-container {  
	text-align: right;  
	margin-top: 20px;  
}  

/* 优化的弹窗样式 */
.visit-dialog {
	border-radius: 12px;
	overflow: hidden;
}

.visit-dialog .el-dialog__header {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	padding: 20px 24px;
	position: relative;
}

.visit-dialog .el-dialog__title {
	color: white;
	font-size: 18px;
	font-weight: 600;
}

.visit-dialog .el-dialog__headerbtn {
	top: 20px;
	right: 20px;
}

.visit-dialog .el-dialog__headerbtn .el-dialog__close {
	color: white;
	font-size: 20px;
}

.visit-dialog .el-dialog__body {
	padding: 0;
	background: #fafbfc;
}

.dialog-header-icon {
	position: absolute;
	top: -10px;
	left: 50%;
	transform: translateX(-50%);
	width: 60px;
	height: 60px;
	background: white;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	z-index: 10;
}

.header-icon {
	font-size: 24px;
	color: #667eea;
}

/* 表单样式 */
.visit-form {
	padding: 40px 30px 20px;
	background: white;
	margin: 0 20px 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.form-section {
	margin-bottom: 32px;
	position: relative;
}

.form-section:last-child {
	margin-bottom: 0;
}

.section-header {
	display: flex;
	align-items: center;
	margin-bottom: 20px;
	padding-bottom: 12px;
	border-bottom: 2px solid #f0f2f5;
	position: relative;
}

.section-header::after {
	content: '';
	position: absolute;
	bottom: -2px;
	left: 0;
	width: 40px;
	height: 2px;
	background: linear-gradient(90deg, #667eea, #764ba2);
	border-radius: 1px;
}

.section-icon {
	font-size: 18px;
	color: #667eea;
	margin-right: 8px;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #2c3e50;
	margin: 0;
}

.section-content {
	padding: 0 4px;
}

/* 表单项样式 */
.required-field .el-form-item__label::before {
	content: '*';
	color: #f56c6c;
	margin-right: 4px;
}

.el-form-item {
	margin-bottom: 22px;
}

.el-form-item__label {
	font-weight: 500;
	color: #606266;
}

.customer-autocomplete {
	width: 100%;
}

.field-tip {
	font-size: 12px;
	color: #909399;
	margin-top: 4px;
	line-height: 1.4;
}

/* 输入框样式优化 */
.el-input__inner,
.el-textarea__inner {
	border-radius: 6px;
	border: 1px solid #dcdfe6;
	transition: all 0.3s;
}

.el-input__inner:focus,
.el-textarea__inner:focus {
	border-color: #667eea;
	box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.el-select {
	width: 100%;
}

.el-select .el-input__inner {
	border-radius: 6px;
}

/* 底部按钮样式 */
.dialog-footer-enhanced {
	padding: 20px 30px;
	background: #fafbfc;
	border-top: 1px solid #ebeef5;
}

.footer-buttons {
	display: flex;
	justify-content: flex-end;
	gap: 12px;
}

.cancel-btn {
	padding: 10px 24px;
	border-radius: 6px;
	font-weight: 500;
	transition: all 0.3s;
}

.cancel-btn:hover {
	background-color: #f5f7fa;
	border-color: #c0c4cc;
}

.submit-btn {
	padding: 10px 24px;
	border-radius: 6px;
	font-weight: 500;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border: none;
	transition: all 0.3s;
}

.submit-btn:hover {
	background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
	transform: translateY(-1px);
	box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.submit-btn:active {
	transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
	.visit-dialog {
		width: 95% !important;
		margin: 0 auto;
	}
	
	.visit-form {
		padding: 30px 20px 15px;
		margin: 0 10px 10px;
	}
	
	.dialog-footer-enhanced {
		padding: 15px 20px;
	}
}

/* 动画效果 */
.el-dialog__wrapper {
	backdrop-filter: blur(2px);
}

.visit-dialog {
	animation: dialogSlideIn 0.3s ease-out;
}

@keyframes dialogSlideIn {
	from {
		opacity: 0;
		transform: translateY(-20px) scale(0.95);
	}
	to {
		opacity: 1;
		transform: translateY(0) scale(1);
	}
}

/* 加载状态 */
.submit-btn.is-loading {
	pointer-events: none;
}
</style>